import {
	createRouter,
	createWebHashHistory
} from 'vue-router'
import store from '@/store'
import {
	h
} from 'vue'

const routes = [{
	path: '/',
	component: () => import('@/views/Layout'),
	children: [{
		path: '/',
		component: () => import('@/views/home/index')
	}, {
		path: '/category/:id',
		component: () => import('@/views/category')
	}, {
		path: '/category/sub/:id',
		component: () => import('@/views/category/sub')
	}, {
		path: '/product/:id',
		component: () => import('@/views/goods/index')
	}, {
		path: '/cart',
		component: () => import('@/views/cart/index')
	}, {
		path: '/member/checkout',
		component: () => import('@/views/member/pay/checkout')
	}, {
		path: '/member/pay',
		component: () => import('@/views/member/pay/index')
	}, {
		path: '/pay/callback',
		component: () => import('@/views/member/pay/result')
	}, {
		path: '/member',
		component: () => import('@/views/member/Layout'),
		children: [{
			path: '/member',
			component: () => import('@/views/member/home')
		}, {
			path: '/member/order',
			// 创建一个RouterView容器形成嵌套关系
			component: {
				render: () => h( < RouterView / > )
			},
			children: [{
				path: '',
				component: () => import('@/views/member/order/index'),
			}, {
				path: ':id',
				component: () => import('@/views/member/order/detail')
			}]
		}]
	}]
}, {
	path: '/login',
	component: () => import('@/views/login/index')
}, {
	path: '/login/callback',
	component: () => import('@/views/login/callback')
}]

const router = createRouter({
	history: createWebHashHistory(),
	routes,
	scrollBehavior() {
		return {
			left: 0,
			top: 0
		}
	}
})

router.beforeEach((to, from, next) => {
	const {
		profile
	} = store.state.user
	if (!profile.token && to.path.startsWith('/member')) {
		return next('/login?redirectUrl=' + encodeURIComponent(to.fullPath))
	}
	next()
})


export default router
